# -*- coding: utf-8 -*-
"""
@Time : 2023/6/7 23:47
@Author : Gremore
@File : register
@Des: 
"""
from fastapp.core import Middleware
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from fastapp.config import settings
from fastapp.config import LOGGING_CONF
from loguru import logger
from fastapi import FastAPI, Request, Depends
from fastapp.router import routers


async def request_info(request: Request):
    logger.bind(name=None).info(f"{request.method} {request.url} {request.headers}")


"""注册路由"""
async def register_routers(_app: FastAPI):
    _app.include_router(routers.router, dependencies=[Depends(request_info)])


"""注册日志"""
def init_logging(logging_conf=LOGGING_CONF):
    for log_handler, log_conf in logging_conf.items():
        log_file = log_conf.pop('file', None)
        logger.add(log_file, **log_conf)


"""注册中间件"""
async def register_middlewares(_app: FastAPI):
    # 中间件
    _app.add_middleware(Middleware.BaseMiddleware)
    # 跨域请求中间件
    _app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGINS,
        allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
        allow_methods=settings.CORS_ALLOW_METHODS,
        allow_headers=settings.CORS_ALLOW_HEADERS,
    )
    # Session中间件
    _app.add_middleware(
        SessionMiddleware,
        secret_key=settings.SECRET_KEY,
        session_cookie=settings.SESSION_COOKIE,
        max_age=settings.SESSION_MAX_AGE
    )
